<?php

include_once "../lime/parse_engine.php";
include_once "python.class";
include_once "python-tokenizer.php";

/* Le definizioni lessicali per python
 * http://docs.python.org/reference/lexical_analysis.html
 * usare con cura...
 */

function tokenize($line) {
	// Numbers are tokens, as are all other non-whitespace characters.
	// Note: This isn't a particularly efficent tokenizer, but it gets the
	// job done.
	$out = array();
	while (strlen($line)) {
		$line = trim($line);
		if (preg_match('/^[0-9]+(\.[0-9]*)?/', $line, $regs)) {
			# It's a number
			$out[] = $regs[0];
			$line = substr($line, strlen($regs[0]));
		} else if (preg_match('/^[A-Za-z]+/', $line, $regs)) {
			# It's a variable name
			$out[] = $regs[0];
			$line = substr($line, strlen($regs[0]));
		} else {
			# It's some other character
			$out[] = $line[0];
			$line = substr($line, 1);
		}
	}
	return $out;
}

$symbol_table = array();
function set_variable($v, $e) {
	global $symbol_table;
	$symbol_table[$v] = $e;
}
function get_variable($v) {
	global $symbol_table;
	return doubleval($symbol_table[$v]);
}



// Main function for run pyton code
function python_eval($pycode) {
	global $parser;
	$line = $pycode;
	if (!strlen($line)) return;
	try {
		$parser->reset();
		foreach(tokenize($line) as $t) {
			if (is_numeric($t)) $parser->eat('num', doubleval($t));
			else if (ctype_alpha($t)) $parser->eat('var', $t);
			else $parser->eat("'$t'", null);
		}
		$parser->eat_eof();
	} catch (parse_error $e) {
		echo $e->getMessage(), "\n";
	}
}

// Main parser object 
$parser = new parse_engine(new python());


/* Start test
 *
 *
 */


// ----------------
// Test 1 - Sample
$code = <<<EOD
t, f = 1, 0
x, y = 88, 99
a = (t and x) or y           # if true, x
print a
a = (f and x) or y           # if false, y
print a
print ((t and [x]) or [y])[0]     # if true, x
print ((f and [x]) or [y])[0]     # if false, y
print (t and f) or y              # fails: f is false, skipped
print ((t and [f]) or [y])[0]     # works: f returned anyhow
EOD;
// Run test 1. 
echo '<pre>';
echo '/* code */'."\n";
var_dump($code);
echo "\n".'/* tokens */'."\n";
var_dump(python_tokenize($code));
echo '</pre>';
//python_eval($code);
// ----------------


// ----------------
// Test 2 - Sample
$code = <<<EOD
	6 ! 5

EOD;
// Run test 2. 
python_eval($code);
// ----------------



?>
